const Service = require('egg').Service
class UserService extends Service {
  // 登录
  async checkPwd({ email, password, role }) {
    const res = await this.ctx.model.User.findOne({
      where: { email, password, role },
      attributes: ['id', 'nickname', 'email', 'balance', 'role']
    })
    return res
  }
  // 注册
  async register({ nickname, email, password, role }) {
    let params = {
      nickname,
      email,
      password,
      role
    }
    let res = await this.ctx.model.User.create(params)
    return {
      id: res.id,
      nickname: res.nickname,
      email: res.email,
      balance: res.balance,
      role: res.role
    }
  }
  // 获取用户信息
  async getInfo({ id, email }) {
    let where = {}
    if (id) {
      where.id = id
    }
    if (email) {
      where.email = email
    }
    let res = await this.ctx.model.User.findOne({
      where,
      attributes: ['id', 'nickname', 'email', 'balance', 'role']
    })
    return res
  }
  // 付款
  async payment({ goods, user_id }, transaction) {
    let sum_price = 0
    for (let item of goods) {
      sum_price += item.goods_num * item.price
    }
    // 查询账户余额
    const balance_res = await this.ctx.model.User.findOne({
      where: { id: user_id }
    })
    if (sum_price > balance_res.balance) {
      throw '余额不足'
    } else {
      const res = await this.ctx.model.query(
        `UPDATE t_user SET balance = balance - :price WHERE id = :user_id`,
        {
          type: 'UPDATE',
          replacements: {
            price: sum_price,
            user_id
          },
          transaction
        }
      )
      return { ...res, balance: balance_res.balance - sum_price }
    }
  }
  // 充值
  async addBalance({ pay_value, user_id }) {
    const res = await this.ctx.model.query(
      `UPDATE t_user SET balance = balance + :pay_value WHERE id = :id`,
      {
        type: 'UPDATE',
        replacements: {
          pay_value: Number(pay_value),
          id: user_id
        }
      }
    )
    // 获取最新的余额
    const user_res = await this.ctx.model.User.findOne({
      where: { id: user_id }
    })
    return user_res
  }
}
module.exports = UserService
